package com.sinodata.bsm.center.web.action.resource;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import net.sf.json.JSONObject;

import com.sinodata.bsm.center.bean.DimensionBean;
import com.sinodata.bsm.center.cache.DimensionCache;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.utils.StringUtil;
import com.sinodata.bsm.common.vo.Dimension;
import com.sinodata.bsm.common.vo.UsabilityValue;

public class ResUsabilityAction extends BaseAction<UsabilityValue> {

    @Autowired
    private DimensionCache dimensionCache;

    /**
     * 构建维度的复杂表头
     * 
     * @param headType
     *            表头类型 top：上表头 left：左表头
     * @param dimensionArray
     *            维度类型的集合数组
     * @return
     */
    private StringBuffer buildTableHead(String headType, String[] dimensionArray, List<DimensionBean> lastDimensionList) {
        //第一维度
        List<Dimension> fistDimensionList = new ArrayList<Dimension>();
        //第二维度
        List<Dimension> secondDimensionList = new ArrayList<Dimension>();
        if (dimensionArray.length > 0 && !StringUtil.isEmpty(dimensionArray[0])) {
            fistDimensionList = dimensionCache.getDimensionParentByType(Long.valueOf(dimensionArray[0]));
        }
        if (dimensionArray.length > 1 && !StringUtil.isEmpty(dimensionArray[1])) {
            secondDimensionList = dimensionCache.getDimensionParentByType(Long.valueOf(dimensionArray[1]));
        }
        //获取两个维度组合下 最大层级
        int dimensionCountDeep = getcountDeep(fistDimensionList, secondDimensionList);
        Map<String, List<DimensionBean>> dimensionBeanMap = new HashMap<String, List<DimensionBean>>();
        //维度数据关系组合
        List<DimensionBean> rootDimensionBean = buldTableData(fistDimensionList, secondDimensionList, dimensionBeanMap, dimensionCountDeep, headType);
        StringBuffer dimensionBuffer = new StringBuffer();
        //顶端是Table的HTML
        if (headType.equals("top")) {
            dimensionBuffer = buldTopHtml(rootDimensionBean, dimensionBeanMap, dimensionCountDeep, lastDimensionList);
        }
        //左边是Div的HTML
        if (headType.equals("left")) {
            dimensionBuffer = buildLeftHtml(rootDimensionBean, dimensionCountDeep, dimensionBeanMap, lastDimensionList);
        }
        return dimensionBuffer;
    }

    /**
     * 构建表格
     */
    public void buildTable() {
        try {
            // 头部维度
            String topDimension = request.getParameter("topDimension");
            //左边维度
            String leftDimension = request.getParameter("lefDimension");
            String[] topDimensionArray = topDimension.split(",");
            String[] leftDimensionArray = leftDimension.split(",");
            //两个List存取 维度最后一行数据 以方便数据存储
            List<DimensionBean> topDimensionList = new ArrayList<DimensionBean>();
            List<DimensionBean> leftDimensionList = new ArrayList<DimensionBean>();
            StringBuffer topdimensionBuffer = buildTableHead("top", topDimensionArray, topDimensionList);
            StringBuffer leftdimensionBuffer = buildTableHead("left", leftDimensionArray, leftDimensionList);
            JSONObject jsonObject = new JSONObject();
            jsonObject.element("topHead", topdimensionBuffer.toString());
            jsonObject.element("leftHead", leftdimensionBuffer.toString());
            jsonObject.element("topdimensionNum", topDimensionList.size());
            jsonObject.element("leftdimensionNum", leftDimensionList.size());
            Struts2Utils.renderText(jsonObject.toString());
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     * 构建维度的数据
     * @param fistDimensionList
     *         第一维度
     * @param secondDimensionList
     *         第二维度
     * @param dimensionBeanMap
     *         维度数据集合
     * @param countDeep
     *         最深深度
     * @param type
     *         顶部和左侧类型
     * @return
     */
    private List<DimensionBean> buldTableData(List<Dimension> fistDimensionList, List<Dimension> secondDimensionList, Map<String, List<DimensionBean>> dimensionBeanMap, int countDeep, String type) {
        Map<String, List<DimensionBean>> rootDimensionMap = new HashMap<String, List<DimensionBean>>();
        List<DimensionBean> lastDimensionBeanList = new ArrayList<DimensionBean>();
        //首选构建第一维度 并且将第一维度最后一层元素存入 lastDimensionBeanList对象中
        for (Dimension dim : fistDimensionList) {
            int level = 1;
            DimensionBean dimensionBean = new DimensionBean(dim);
            dimensionBean.setLevel(level);
            buildDimensionRelation(dimensionBean, lastDimensionBeanList);
            String key = "root";
            buildMapData(dimensionBean, rootDimensionMap, key);
        }

        // 在lastDimensionBeanList的基础上 与第二维度关联
        for (DimensionBean lastBean : lastDimensionBeanList) {
            if (secondDimensionList != null) {
                for (Dimension dimension : secondDimensionList) {
                    DimensionBean db = new DimensionBean(dimension);
                    int level = lastBean.getLevel() + 1;
                    db.setLevel(level);
                    db.setParentDimensionBean(lastBean);
                    buildDimensionRelation(db, null);
                    lastBean.getDimensionBeanList().add(db);
                }
            }
        }

        // 处理父级的特殊情况 在最后一行添加父级的TD
        List<DimensionBean> rootDimensionBean = rootDimensionMap.get("root");
        for (int i = 0; i < rootDimensionBean.size(); i++) {
            DimensionBean rootBean = rootDimensionBean.get(i);
            processParentSpecialHead(rootBean, countDeep);
        }

        // 根据孩子的多少设置TD的colspan属性
        // 赞为考虑特殊情况 rowspan的情况
        for (int i = 0; i < rootDimensionBean.size(); i++) {
            DimensionBean rootBean = rootDimensionBean.get(i);
            String key = "";
            // 上表头的情况 用层级作为健值
            if (type.equals("top")) {
                key = String.valueOf(rootBean.getLevel());

                // 左表头的情况 用最根元素ID+层级 为健值
            } else {
                key = String.valueOf(rootBean.getLevel()) + "#" + rootBean.getDimension().getId();
            }
            buildMapData(rootBean, dimensionBeanMap, key);
            int colspan = buildDimensionColspan(rootBean, dimensionBeanMap, rootBean.getDimension().getId(), type);
            rootBean.setColspan(colspan);
        }
        return rootDimensionBean;
    }

    /**
     * 获取当前维度的层次(两个维度的累加)
     * 
     * @param fistDimensionList
     * @param secondDimensionList
     * @return
     */
    private int getcountDeep(List<Dimension> fistDimensionList, List<Dimension> secondDimensionList) {
        int countDeep = 0;
        // 算出每个维度的层次，最后将层次累加就是当前表头的行
        for (Dimension dimens : fistDimensionList) {
            List<Dimension> childDimension = dimensionCache.getDimensionByParentId(dimens.getId());
            int maxXdeep = findDisionMaxDeep(childDimension, 1);
            if (maxXdeep > countDeep)
                countDeep = maxXdeep;
        }
        int maxZdeep = 0;
        if (secondDimensionList != null) {
            for (Dimension dimens : secondDimensionList) {
                List<Dimension> childDimension = dimensionCache.getDimensionByParentId(dimens.getId());
                int deep = findDisionMaxDeep(childDimension, 1);
                if (deep > maxZdeep)
                    maxZdeep = deep;
            }
        }
        // 整个表格有多少行
        countDeep += maxZdeep;
        return countDeep;
    }

    /**
     * 构建顶部表格的HTML
     * 
     * @param rootDimensionBean
     *            根维度
     * @param dimensionBeanMap
     *            数据集合Map
     * @param countDeep
     *            最大层级
     * @param lastDimensionlist
     *            最后一行的对象集合(方便数据操作)
     * @return
     */
    private StringBuffer buldTopHtml(List<DimensionBean> rootDimensionBean, Map<String, List<DimensionBean>> dimensionBeanMap, int countDeep, List<DimensionBean> lastDimensionlist) {
        StringBuffer htmlBuffer = new StringBuffer();
        Object[] mapkey = dimensionBeanMap.keySet().toArray();
        Arrays.sort(mapkey);
        // StringBuffer htmlBuffer = new StringBuffer();
        for (int i = 0; i < mapkey.length; i++) {
            String key = (String) mapkey[i];
            List<DimensionBean> dimensionBeanList = dimensionBeanMap.get(key);
            StringBuffer trBuffer = new StringBuffer();
            trBuffer.append("<tr class=\"tr" + key + "\">" + "\r\n");
            for (DimensionBean dim : dimensionBeanList) {
                trBuffer.append("<th ");
                if (dim.getColspan() > 0) {
                    trBuffer.append(" colspan=" + dim.getColspan());
                }
                if (dim.getRowspan() > 0) {
                    trBuffer.append(" rowspan=" + dim.getRowspan());
                }
                trBuffer.append(">");
                trBuffer.append(dim.getDimension().getDimensionName());
                trBuffer.append("</th>" + "\r\n");
                if (key.equals(String.valueOf(countDeep)))
                    lastDimensionlist.add(dim);
            }
            trBuffer.append("</tr>" + "\r\n");
            htmlBuffer.append(trBuffer);
        }
        System.out.println(htmlBuffer.toString());
        return htmlBuffer;
    }

    /**
     * 动态生成表格的左侧项和顶部头项
     * 
     * @param rootDimensionBean
     *            根部对象
     * @param showType
     *            1--生成左侧 2---生成头部
     * @param countDeep
     *            整个层次
     * @param dimensionBeanMap
     *            以顶部+当前层级为key的Map对象
     * @return
     */
    private StringBuffer buildLeftHtml(List<DimensionBean> rootDimensionBean, int countDeep, Map<String, List<DimensionBean>> dimensionBeanMap, List<DimensionBean> lastDimensionlist) {
        // Div 拼接
        StringBuffer htmlBuffer = new StringBuffer();
        String colspanType = "height:";

        // 设置默认的高度为27像素
        double colspanHeight = 27;
        for (int i = 0; i < rootDimensionBean.size(); i++) {
            DimensionBean rootBean = rootDimensionBean.get(i);
            StringBuffer rootBuffer = new StringBuffer();
            rootBuffer.append(" <div class=\"fistDiv\">");
            double cospanValue = rootBean.getColspan() * colspanHeight;
            cospanValue += rootBean.getColspan() - 2;
            rootBuffer.append(" <div class=\"Text\" style=\"" + colspanType + "" + cospanValue + "px\">");
            rootBuffer.append(rootBean.getDimension().getDimensionName());
            rootBuffer.append("</div>");
            int index = rootBean.getLevel() + 1;
            while (index <= countDeep) {
                String key = index + "#" + String.valueOf(rootBean.getDimension().getId());
                List<DimensionBean> dimensionBeanList = dimensionBeanMap.get(key);
                if (dimensionBeanList != null && dimensionBeanList.size() > 0) {
                    StringBuffer childBuffer = new StringBuffer();
                    // 第二行 第二行与其他样式不一样
                    if (index == 2)
                        childBuffer.append(" <div class=\"secondDiv\">" + "\r\n");
                    else if (index == countDeep)
                        childBuffer.append(" <div class=\"last\">" + "\r\n");
                    else
                        childBuffer.append(" <div class=\"third\">" + "\r\n");
                    for (int j = 0; j < dimensionBeanList.size(); j++) {
                        DimensionBean dim = dimensionBeanList.get(j);
                        double childSpanvalue = dim.getColspan() * colspanHeight;
                        // 不是最后一行 减去边框
                        if (index != countDeep) {
                            childSpanvalue += dim.getColspan() - 1;
                        }
                        childBuffer.append(" <span ");
                        if (dim.getColspan() > 0) {
                            childBuffer.append("  style=\"" + colspanType + "" + childSpanvalue + "px\"");
                        }
                        childBuffer.append(">" + dim.getDimension().getDimensionName());
                        childBuffer.append("</span>");
                        // 最后一行的元素加入List中
                        if (index == countDeep)
                            lastDimensionlist.add(dim);

                    }
                    childBuffer.append("</div>");
                    rootBuffer.append(childBuffer);
                }
                index++;
            }
            rootBuffer.append("</div>");
            htmlBuffer.append(rootBuffer);
        }
        return htmlBuffer;
    }

    /**
     * 构建维度关系
     * 
     * @param dimensionbean
     * @param maxDeep
     * @param dimensionBeanMap
     * @param tempdimensionBeanList
     */
    private void buildDimensionRelation(DimensionBean dimensionbean, List<DimensionBean> lastDimensionBeanList) {
        List<Dimension> childDimension = dimensionCache.getDimensionByParentId(dimensionbean.getDimension().getId());
        for (Dimension dimens : childDimension) {
            DimensionBean childDimensionBean = new DimensionBean(dimens);
            childDimensionBean.setParentDimensionBean(dimensionbean);
            int level = dimensionbean.getLevel() + 1;
            childDimensionBean.setLevel(level);
            dimensionbean.getDimensionBeanList().add(childDimensionBean);
            buildDimensionRelation(childDimensionBean, lastDimensionBeanList);
        }
        if (lastDimensionBeanList != null) {
            if ((childDimension == null || childDimension.size() == 0)) {
                lastDimensionBeanList.add(dimensionbean);
            }
        }
    }

    /**
     * 查找它的最深层
     * 
     * @param dimensionList
     * @param maxDeep
     * @return
     */
    private int findDisionMaxDeep(List<Dimension> dimensionList, int maxDeep) {
        if (dimensionList != null && dimensionList.size() > 0) {
            maxDeep++;
            for (Dimension dimension : dimensionList) {
                List<Dimension> childDimension = dimensionCache.getDimensionByParentId(dimension.getId());
                if (childDimension != null && childDimension.size() > 0) {
                    int temMax = findDisionMaxDeep(childDimension, maxDeep);
                    if (temMax > maxDeep)
                        maxDeep = temMax;
                }
            }
        }
        return maxDeep;
    }

    /**
     * 构建Map集合
     * 
     * @param dimensionBean
     * @param dimensionBeanMap
     */
    public void buildMapData(DimensionBean dimensionBean, Map<String, List<DimensionBean>> dimensionBeanMap, String key) {
        List<DimensionBean> dimensionBeanList = dimensionBeanMap.get(key);
        if (dimensionBeanList == null) {
            dimensionBeanList = new ArrayList<DimensionBean>();
        }
        dimensionBeanList.add(dimensionBean);
        dimensionBeanMap.put(key, dimensionBeanList);
    }

    /**
     * 
     * 处理复杂的父类表头
     * 
     * @param dimensionBean
     */
    public DimensionBean processParentSpecialHead(DimensionBean dimensionBean, int countDeep) {
        List<DimensionBean> childDimensionBean = dimensionBean.getDimensionBeanList();
        if (childDimensionBean != null) {
            for (int i = 0; i < childDimensionBean.size(); i++) {
                DimensionBean childDim = childDimensionBean.get(i);
                // 到了最后的一行的情况
                if (childDim.getDimensionBeanList() == null || childDim.getDimensionBeanList().size() == 0) {
                    if (i == childDimensionBean.size() - 1) {
                        addPararentTd(dimensionBean, dimensionBean, countDeep);
                        break;
                    }
                } else {
                    processParentSpecialHead(childDim, countDeep);
                    if (i == childDimensionBean.size() - 1) {
                        addPararentTd(childDim, dimensionBean, countDeep);
                        break;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 将特殊的父亲对象 加入最后一行
     * 
     * @param childDimensionBean
     *            最后一行子元素
     * @param parentdimensionBean
     *            父元素
     * @param countDeep
     *            最深层级
     * @return
     */
    public DimensionBean addPararentTd(DimensionBean childDimensionBean, DimensionBean parentdimensionBean, int countDeep) {
        if (parentdimensionBean != null) {
            DimensionBean parentDimensionBean = new DimensionBean(parentdimensionBean.getDimension());
            parentDimensionBean.setLevel(countDeep);
            if (countDeep - 1 == childDimensionBean.getLevel()) {
                childDimensionBean.getDimensionBeanList().add(parentDimensionBean);
            } else {
                // 这里只处理四层的情况 理论上要去递归的
                int size = childDimensionBean.getDimensionBeanList().size() > 0 ? childDimensionBean.getDimensionBeanList().size() : 0;
                DimensionBean dim = childDimensionBean.getDimensionBeanList().get((size - 1));
                if (dim != null) {
                    dim.getDimensionBeanList().add(parentDimensionBean);
                }

            }

        }
        return null;
    }

    /**
     * 构建维度的Colspan对象
     * 
     * @param dimensionBean
     *            维度对象
     * @param dimensionBeanMap
     *            数据集合Map对象 上表头：健为当前level 左表头为：根维度Id+"#"+当前level
     * @param rootKey
     *            根元素的维度对象
     * @param type
     *            区分上表头和左侧表头
     * @return
     */
    public int buildDimensionColspan(DimensionBean dimensionBean, Map<String, List<DimensionBean>> dimensionBeanMap, Long rootKey, String type) {
        int colspan = 0;
        List<DimensionBean> dimensionBeanList = dimensionBean.getDimensionBeanList();
        for (int i = 0; i < dimensionBeanList.size(); i++) {
            DimensionBean dim = dimensionBeanList.get(i);
            String key = "";
            // 不同健值
            if (type.equals("top")) {
                key = String.valueOf(dim.getLevel());
            } else {
                key = String.valueOf(dim.getLevel()) + "#" + rootKey;
            }
            buildMapData(dim, dimensionBeanMap, key);
            // 递归 设置colspan对象
            if (dim.getDimensionBeanList().size() > 0) {
                int temColspan = buildDimensionColspan(dim, dimensionBeanMap, rootKey, type);
                dim.setColspan(temColspan);
                colspan += dim.getColspan();
            } else {
                colspan += 1;
            }
        }
        // 到最后一层
        if (dimensionBeanList == null || dimensionBeanList.size() == 0)
            return colspan;
        return colspan;
    }

    @Override
    public String delete() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String input() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String list() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected void prepareModel() throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public String save() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public UsabilityValue getModel() {
        // TODO Auto-generated method stub
        return null;
    }

}
